package com.his.server.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
import java.lang.Class;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.his.server.consts.ServerConsts;
import com.his.server.exception.DBException;
import com.his.server.utils.main.EnvironmentProperties;

public class DBConnectionPool implements ConnectionPool {
	
    private static final Log logger;
	private static List <Connection> pool;
	
	static 
    {
        logger = LogFactory.getLog(DBConnectionPool.class);
    }
	
	public synchronized Connection getConnction() throws DBException {
		
		Connection connect;

		if (pool == null) {
			pool = new ArrayList <Connection> ();
		}
		
		if (pool.isEmpty()) {
			connect = createConnction(); 
		} else {
			int conn_indext = pool.size() - 1;
			connect = pool.get(conn_indext);
			pool.remove(pool.get(conn_indext));
		}
		
		ConnectionHandler connectHandler = new ConnectionHandler(this);
		return connectHandler.Bind(connect);		
	}
	
    public synchronized void releaseConnction(Connection connect) throws DBException {
    	
    	String db_pool_max_sise = EnvironmentProperties.
    			getEproperties().getPropertyList().get(0).getProperty(ServerConsts.DB_POOL_MAX_SIZE);   	
    	Integer maxsise = new Integer(db_pool_max_sise);
    	
    	if (pool.size() > maxsise) {
    		if (connect != null) {
    			try {
        			connect.close();
        		} catch (SQLException ex) {

        			throw new DBException("SQLException when release JDBC Driver", ex);
        		}
    		}   		
    	} else {
    		pool.add(connect);
    	}
    }
    
    public Connection createConnction() throws DBException{
    	
    	Connection connect = null;
    	String db_driver_name = EnvironmentProperties.
    			getEproperties().getPropertyList().get(0).getProperty(ServerConsts.DB_DRIVER_NAME);
    	
    	String db_url = EnvironmentProperties.
    			getEproperties().getPropertyList().get(0).getProperty(ServerConsts.DB_URL);
    	
    	String db_user = EnvironmentProperties.
    			getEproperties().getPropertyList().get(0).getProperty(ServerConsts.DB_USER);
    	
    	String db_password = EnvironmentProperties.
    			getEproperties().getPropertyList().get(0).getProperty(ServerConsts.DB_PASSWORD);
    	
    	try {
    		
            Class.forName(db_driver_name);
            connect = DriverManager.getConnection(db_url, db_user, db_password);

    	} catch (ClassNotFoundException ex) {
            
    		throw new DBException("ClassNotFoundException when loading JDBC Driver", ex);
    	} catch (SQLException ex) {
    		
    		throw new DBException("SQLException when loading JDBC Driver", ex);
    	}
    	
        return connect;
    }
	
}